package com.zyh.flink.day02.sink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringEncoder;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.core.fs.Path;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink;
import org.apache.flink.util.Collector;

public class SinkToHDFSTest {
    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> hadoop10 = executionEnvironment.socketTextStream("hadoop10", 9999);
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = hadoop10.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = s.split("\\s+");
                for (String word : words) {
                    collector.collect(Tuple2.of(word, 1));
                }
            }
        }).keyBy(t -> t.f0)
                .sum(1);
        //向hdfs输出
        Path basePath = new Path("hdfs://hadoop10:9000/flink-sink");
        SimpleStringEncoder<Tuple2<String, Integer>> stringEncoder = new SimpleStringEncoder<>();//将要输出的每一个元素的toString方法的返回值输出到文件中
        StreamingFileSink<Tuple2<String, Integer>> fileSink = StreamingFileSink.forRowFormat(basePath, stringEncoder).build();
        result.addSink(fileSink);
        executionEnvironment.execute("fileSinkJob");
    }
}
